% safe参数解决与\!在内的多个冲突
% \sups命令可能被重定义,xeCJK放在tipa后
\RequirePackage[safe]{tipa}

\documentclass[a4paper, zihao=-4, linespread=1]{ctexrep}
\renewcommand{\CTEXthechapter}{\thechapter}
% 最小行间间距设定
\setlength{\lineskiplimit}{3pt}
\setlength{\lineskip}{3pt}

% 中文支持
\setCJKmainfont[BoldFont=Source Han Serif SC Bold]{Source Han Serif SC}
  \xeCJKsetup{CJKmath=true}
  \setCJKmathfont{KaiTi}  % 数学环境中使用楷体
\newCJKfontfamily[zhxinwei]\xinwei{STXinwei} % 定义新字体

% 颜色
\usepackage[table]{xcolor}
  \newcommand{\scol}[1]{\colorbox{#1}{\rule{0em}{1ex}}\,#1}
  
% 首字下沉
\usepackage{lettrine}

% 分栏
\usepackage{multicol}
  \setlength{\columnsep}{20pt}
  \setlength{\columnseprule}{0.4pt}

% 数学环境
\usepackage{mathdots} % 数学省略号，会重定义 dddot 和 ddddot
\usepackage{amsmath}  
  \newcommand{\ue}{\mathrm{e}}
  \newcommand{\ud}{\mathop{}\negthinspace\mathrm{d}} % 微分号
\usepackage{amssymb}
\usepackage{mathrsfs} % 线性代数字体
% overline的替代命令
\newcommand{\closure}[2][3]{{}\mkern#1mu\overline{\mkern-#1mu#2}}
\usepackage{yhmath} % \wideparen命令：弧AB
\usepackage{mathtools} % dcases环境，prescript命令
\usepackage{amsthm} % 定理环境
  \theoremstyle{definition}\newtheorem{laws}{Law}[section]
  \theoremstyle{plain}\newtheorem{ju}[laws]{Jury}
  \theoremstyle{remark}\newtheorem*{marg}{Margaret}
\usepackage{esint} % 多重积分，需放在amsmath后
% 箭头与长等号
\usepackage{extarrows}
% 中括号的类二项式命令
\newcommand{\Bfrac}[2]{\genfrac{[}{]}{0pt}{}{#1}{#2}}

% 下划线宏包
\usepackage[normalem]{ulem}
% LaTeX符号宏包
\usepackage{hologo}
	\newcommand{\xelatex}{\Hologo{XeLaTeX}}
  \newcommand{\bibtex}{\Hologo{BibTeX}}
  \newcommand{\biber}{\Hologo{biber}}
	\newcommand{\tikzz}{Ti\textit{k}Z}
	\newcommand{\bz}{B\'ezier}
% 其他符号
\usepackage{wasysym}
% 带箱小页
\usepackage{boxedminipage}
% 绘图
\usepackage{tikz}
  \usetikzlibrary{calc,intersections,positioning,angles,quotes,decorations.pathmorphing,fit,backgrounds,through,svg.path,topaths,patterns}
  \newcommand{\tikzline}[1]{{#1\tikz{\draw[#1,line width=9](0,0)--(0.5,0);}}, }
% 最后一页
\usepackage{lastpage}

% 奇怪的小定义
\newcommand{\dpar}{\\ \mbox{}}  % 空两行
\newcommand{\qd}[1]{{\bfseries{#1}}}  % 强调
\newcommand{\co}[1]{{\bfseries{#1}}}  % Style of concept
\newcommand{\RED}[1]{{\color{cyan}{#1}}}
\newcommand{\cmmd}[1]{\fbox{\texttt{\char92{}#1}}}
\newcommand{\charef}[1]{第\ref{#1}章}
\newcommand{\secref}[1]{第\ \ref{#1}\ 节}
\newcommand{\pref}[1]{第\pageref{#1}页}
\newcommand{\fref}[1]{图\ref{#1}}
\newcommand{\tref}[1]{表\ref{#1}}

% Quote 环境
\newenvironment{QuoteEnv}[2][]
    {\newcommand\Qauthor{#1}\newcommand\Qref{#2}}
    {\medskip\begin{flushright}\small ——~\Qauthor\\
    \emph{\Qref}\end{flushright}}
% 字体调用
\newcommand{\myfont}[2]{{\fontfamily{#1}\selectfont #2}}

% 编号列表宏包，并自定义了三个列表
\usepackage[inline]{enumitem}
	\setlist[enumerate]{font=\bfseries,itemsep=0pt}
	\setlist[itemize]{font=\bfseries,leftmargin=\parindent}
	\setlist[description]{font=\bfseries\uline,labelindent=\parindent,itemsep=0pt,parsep=0pt,topsep=0pt,partopsep=0pt}

\newenvironment{fead}{	
    \begin{description}[font=\bfseries\uline,labelindent=\parindent,itemsep=0pt,parsep=0pt,topsep=0pt,partopsep=0pt]}
	{\end{description}}
% 带宽度的
\newenvironment{para}{
	\begin{description}[font=\bfseries\ttfamily,itemsep=0pt,parsep=0pt,topsep=0pt,partopsep=0pt]}
	{\end{description}}
\newenvironment{feae}{
	\begin{enumerate}[font=\bfseries,labelindent=0pt,itemsep=0pt,parsep=0pt,topsep=0pt,partopsep=0pt]}
	{\end{enumerate}}
\newenvironment{feai}{
	\begin{itemize}[font=\bfseries,itemsep=0pt,parsep=0pt,topsep=0pt,partopsep=0pt]}
	{\end{itemize}}
\newenvironment{inlinee}
{\begin{enumerate*}[label=(\arabic*), font=\rmfamily, before=\unskip{：},itemjoin={{；}},itemjoin*={{，以及：}}]}
	{\end{enumerate*}。}

% 目录和章节样式
\usepackage{titlesec}
\usepackage{titletoc}   % 用于目录

\titlecontents{chapter}[1.5em]{}{\contentslabel{1.5em}}{\hspace*{-2em}}{\hfill\contentspage}
\titlecontents{section}[3.3em]{}{\contentslabel{1.8em}}
	{\hspace*{-2.3em}}{\titlerule*[8pt]{$\cdot$}\contentspage}
\titlecontents*{subsection}[2.5em]{\small}{\thecontentslabel{} }{}{, \thecontentspage}[;\qquad][.]
% 章节样式
\setcounter{secnumdepth}{3} % 一直到subsubsection
\newcommand{\chaformat}[1]{%
	\parbox[b]{.5\textwidth}{\hfill\bfseries #1}%
	\quad\rule[-12pt]{2pt}{70pt}\quad
	{\fontsize{60}{60}\selectfont\thechapter}}
\titleformat{\chapter}[block]{\hfill\LARGE\sffamily}{}{0pt}{\chaformat}[\vspace{2.5pc}\normalsize
	\startcontents\setlength{\lineskiplimit}{0pt}\printcontents{}{1}{\setcounter{tocdepth}{2}\songti}]
\titleformat*{\section}{\centering\Large\bfseries}
\titleformat{\subsubsection}[hang]{\bfseries\large}{\rule{1.5ex}{1.5ex}}{0.5em}{}
% 扩展章节
\newcommand{\starsec}{\noindent\fbox{\S\textit{注意：本章节是一个扩展阅读章节。}}
	\\ \mbox{}}

\renewcommand{\contentsname}{目录}
	\renewcommand{\tablename}{表}
	\renewcommand\arraystretch{1.2}	% 表格行距
	\renewcommand{\figurename}{图}
% 设置不需要浮动体的表格和图像标题
\setlength{\abovecaptionskip}{5pt}
\setlength{\belowcaptionskip}{3pt}
\makeatletter
\newcommand\figcaption{\def\@captype{figure}\caption}
\newcommand\tabcaption{\def\@captype{table}\caption}
\makeatother
% 图表
\usepackage{array,multirow,makecell}
  \setlength\extrarowheight{2pt} % 行高增加
\usepackage{diagbox}
\usepackage{longtable}
\usepackage{graphicx,wrapfig}
  \graphicspath{{./tikz/}}
\usepackage{animate}
\usepackage{caption,subcaption}
  \captionsetup[sub]{labelformat=simple}
  \renewcommand{\thesubtable}{(\alph{subtable})}
% 三线表
\usepackage{booktabs}  

% 页面修正宏包
\usepackage{geometry}
  \geometry{vmargin = 1in}

% 代码环境
\usepackage{listings}
% 复制代码时不复制行号
\usepackage{accsupp}
  \newcommand{\emptyaccsupp}[1]{\BeginAccSupp{ActualText={}}#1\EndAccSupp{}}
\usepackage{tcolorbox}
  \tcbuselibrary{listings,skins,breakable,xparse}

% global style
\lstset{
  basicstyle=\small\ttfamily,
  % Word styles
  keywordstyle=\color{blue},
  commentstyle=\color{green!50!black},
  columns=fullflexible,  % Avoid too sparse word spaces
  keepspaces=true,
  % Numbering
  numbers=left,
  numberstyle=\tiny\color{red!75!black}\emptyaccsupp,
  % Lines and Skips
  aboveskip=0pt plus 6pt,
  belowskip=0pt plus 6pt,
  breaklines=true,
  breakatwhitespace=true,
  emptylines=1,  % Avoid >1 consecutive empty lines
  escapeinside=``
}

% TikZ Language Hint
\lstdefinelanguage{tikzlang}{
  sensitive=true,
  morecomment=[n]{[}{]}, % nested comment
  morekeywords={
    draw,clip,filldraw,path,node,coordinate,foreach,pic,
    tikzset
  }
}

% 对于 tcolorbox 中 listings 库的 ''tcblatex'' style 的重现，
% 添加了新的关键词
\lstdefinestyle{latexcn}{
  language=[LaTeX]TeX,
  % More Keywords
  classoffset=0,
  texcsstyle=*\color{blue},
  moretexcs={
    % LaTeX extension
    chapter,section,subsection,setlength,
    thechapter,thesection,thesubsection,theequation,
    chaptermark,chaptername,appendix,
    bibname,refname,bibpreamble,bibfont,citenumfont,bibnumfmt,bibsep,
  },
  classoffset=1,
  texcsstyle=*\color{orange!75!black},
  moretexcs={
    % XeCJK & CTeX
    xeCJKsetup,setCJKmainfont,newCJKfontfamily,CJKfontspec,
    CTEXthechapter,songti,heiti,fangsong,kaishu,yahei,lishu,youyuan,
    % AMSmath / AMSsymb / AMSthm
    middle,text,tag,boldsymbol,mathbb,dddot,ddddot,iint,varoiint,
    dfrac,tfrac,cfrac,leftroot,uproot,underbracket,xleftarrow,xrightarrow,
    overset,underset,sideset,mathring,leqslant,geqslant,because,therefore,
    shortintertext,binom,dbinom,implies,thesubequation,
    impliedby,genfrac,theoremstyle,qedhere,
    % Other math packages
    wideparen,intertext,
    xlongequal,xLeftrightarrow,xleftrightarrow,xLongleftarrow,xLongrightarrow,
    % xcolor
    definecolor,color,textcolor,colorbox,fcolorbox,
    % hyperref
    hyperref,autoref,href,url,nolinkurl,
  　　% Graph & Table
    includegraphics,graphicspath,scalebox,rotatebox,animategraphics,
    newcolumntype,arraybackslash,multirow,captionsetup,
    thead,multirowcell,makecell,Xhline,Xcline,diagbox,
    toprule,midrule,bottomrule,DeclareFloatingEnvironment,
    % ulem
    uline,uuline,dashuline,dotuline,uwave,sout,xout,
    % fancyhdr
    lhead,chead,rhead,lfoot,cfoot,rfoot,
    fancyhf,fancyhead,fancyfoot,fancypagestyle,
    % fontspec
    newfontfamily,
    % titlesec & titletoc
    titlelabel,titleformat,titlespacing,titleline,titlerule,dottecontents,titlecontents,
    % enumitem
    setlist,
    % Listings & tcolorbox
    lstdefinelanguage,lstdefinestyle,lstset,lstnewenvironment,
    tcbuselibrary,newtcblisting,newtcbox,DeclareTCBListing
    % citation & index: natbib, imakeidx
    setcitestyle,printindex,
    % Other packages
    hologo,lettrine,endfirsthead,endhead,endlastfoot,columncolor,rowcolors,modulolinenumbers,MakeShortVerb,tikz,Hologo
  }
}

% cmd & envi
\newtcbox{\latexline}[1][green]{on line,before upper=\ttfamily\char`\\,
  arc=0pt,outer arc=0pt,colback=#1!10!white,colframe=#1!50!black,
  boxsep=0pt,left=1pt,right=1pt,top=1pt,bottom=1pt,
  boxrule=0pt,bottomrule=1pt,toprule=1pt}
\newtcbox{\envi}[1][violet!70!cyan]{on line,before upper=\ttfamily,
  arc=0pt,outer arc=0pt,colback=#1!10!white,colframe=#1!50!black,
  boxsep=0pt,left=1pt,right=1pt,top=1pt,bottom=1pt,
  boxrule=0pt,bottomrule=1pt,toprule=1pt}
% pkg
\newtcbox{\pkg}[1][orange!70!red]{on line,before upper={\rule[-0.2ex]{0pt}{1ex}\ttfamily},
  arc=0.8ex,colback=#1!30!white,colframe=#1!50!black,
  boxsep=0pt,left=1.5pt,right=1.5pt,top=1pt,bottom=1pt,
  boxrule=1pt}
\newcommand{\tikzkw}[1]{\texttt{#1}}

% tcblisting definitions
\newtcblisting{latex}{breakable,skin=bicolor,colback=gray!30!white,
  colbacklower=white,colframe=cyan!75!black,listing only, 
  left=6mm,top=2pt,bottom=2pt,fontupper=\small,
  listing options={style=latexcn}
}

\NewTCBListing{codeshow}{ !O{listing side text} }{
  skin=bicolor,colback=gray!30!white,
  colbacklower=pink!50!yellow,colframe=cyan!75!black,
  valign lower=center,
  left=6mm,righthand width=0.4\linewidth,fontupper=\small,
  % listing style
  listing options={style=latexcn},#1,
}

% Fix solution from the tcolorbox package author
\makeatletter
\tcbset{
  tikz upper/.style={before upper=\centering\tcb@shield@externalize\begin{tikzpicture}[{#1}],after upper=\end{tikzpicture}},%
  tikz lower/.style={before lower=\centering\tcb@shield@externalize\begin{tikzpicture}[{#1}],after lower=\end{tikzpicture}},%
}
\makeatother

% xparse library required
\NewTCBListing{tikzshow}{ O{} }{
  tikz lower={#1},
  halign lower=center,valign lower=center,
  skin=bicolor,colback=gray!30!white,
  colbacklower=white,colframe=cyan!75!black, 
  left=6mm,righthand width=3.5cm,listing outside text,
  listing options={language=tikzlang}
}

\NewTCBListing{tikzshowenvi}{ O{} }{
  halign lower=center,valign lower=center,
  skin=bicolor,colback=gray!30!white,
  colbacklower=white,colframe=cyan!75!black, 
  left=6mm,righthand width=3.5cm,listing outside text,
  listing options={language=tikzlang},#1
}
% inline tikz draw
%\newcommand{\tikzline}{def}

% 附录
% \usepackage{appendix}
\renewcommand{\appendixname}{App.}

% 行号
\usepackage{lineno}

% 索引与参考文献
\usepackage{imakeidx}
  \newcommand{\tikzidx}[1]{\index{\char`\\ #1}}
  \newcommand{\tikzoptstyle}[1]{\texttt{#1}}
  \newcommand{\tikzopt}[2][draw]{\tikzoptstyle{#2}\index{\char`\\ #1!#2}\ }
  \renewcommand{\indexname}{\tikzz 命令索引}
\makeindex[intoc]

\bibliographystyle{plain}
\renewcommand{\bibname}{参考文献}
\usepackage[numindex,numbib]{tocbibind}
\usepackage[square,super,sort&compress]{natbib}

% 引用
\usepackage{hyperref}
\hypersetup{colorlinks, bookmarksopen = true, bookmarksnumbered = true, pdftitle=LaTeX-cn, pdfauthor=K.L Wu, pdfstartview=FitH}
